package server;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * @author: wudong
 * @create: 2021-07-26 17:03
 **/
public class Endpoint implements Lifecycle{
    private final int port;

    private final Handler handler;

    private ServerSocket serverSocket;

    public Endpoint(int port,Handler handler) {
        this.port = port;
        this.handler = handler;
    }


    @Override
    public void init() throws Exception {

    }

    @Override
    public void start() throws Exception{
        if(serverSocket != null){
            return;
        }else {
            serverSocket = new ServerSocket(port);
        }
        System.out.println("=====>>>Minicat start on port：" + port);

        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                while(true) {
                    try {
                        Socket socket = serverSocket.accept();
                        process(socket);
                    } catch (IOException e) {
                        System.out.println("======>>>accept on port:" + port + ",error");
                    }

                }
            }
        }, "Endpoint-Acceptor");
        t.setPriority(Thread.NORM_PRIORITY);
        t.setDaemon(false);
        t.start();

    }


    private void process(Socket socket){
        this.handler.process(socket);
    }
}
